import {AfterViewInit, Component, ElementRef, Input, OnInit} from '@angular/core';
import {AlertOptions} from './alert';
import {timer} from 'rxjs';

@Component({
  selector: 'ng-tools-alert',
  templateUrl: './alert.component.html',
  styleUrls: ['./alert.component.scss']
})
export class AlertComponent implements OnInit, AfterViewInit {
  @Input() options: AlertOptions;

  id: string;
  dom: JQuery<HTMLElement>;

  constructor(private elemRef: ElementRef) {
    this.id = `alert-${new Date().getTime()}`;
  }

  ngOnInit() {
    timer(0).subscribe(() => {
      this.dom = $(this.elemRef.nativeElement).find(`#${this.id}`);
    });
  }

  show(options: AlertOptions, time?: number) {
    /**
     * 带time参数会自动调用hide()方法
     * */
    this.options.theme = options.theme || 'success';
    this.options.data = options.data;
    this.dom.alert();
    if (time) {
      this.hide(time);
    }
  }

  hide(time: number = 0) {
    timer(time).subscribe(() => {
      this.dom.alert('close');
      this.options.data = null;
      this.options.dynamicComponent = null;
    });
  }


  ngAfterViewInit(): void {
  }
}
